package v1

import (
	log "auth/collector/logger"
	"auth/config"
	"auth/constants"
	"auth/utils"
	"auth/utils/httputil"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

var (
	routerRulesMap = map[string]bool{
		"/:name":                                                       true,
		"/:name/:name":                                                 true,
		"/:name/:name/:name":                                           true,
		"/:name/:name/:name/:name":                                     true,
		"/:name/:name/:name/:name/:name":                               true,
		"/:name/:name/:name/:name/:name/:name":                         true,
		"/:name/:name/:name/:name/:name/:name/:name":                   true,
		"/:name/:name/:name/:name/:name/:name/:name/:name":             true,
		"/:name/:name/:name/:name/:name/:name/:name/:name/:name":       true,
		"/:name/:name/:name/:name/:name/:name/:name/:name/:name/:name": true,
	}
)

var Handler = &handler{}

func init() {
	RegisterRouter(Handler)
}

type handler struct {
}

// Init 初始化路由
func (a *handler) Init(r *gin.RouterGroup) {

}

// Handler 默认路由
func (a *handler) Handler(ctx *gin.Context) {
	defer utils.ExceptionCatch()
	var (
		err error
	)

	data, err := ctx.GetRawData()
	if err != nil {
		return
	}

	userId := ""
	if v, ok := ctx.Get(constants.UserId); ok {
		userId = v.(string)
	}

	deviceId := ""
	if v, ok := ctx.Get(constants.DeviceId); ok {
		deviceId = v.(string)
	}

	// 转发请求
	request := ctx.Request
	path := request.RequestURI
	url := config.Conf.Misc.GatewayUrl + path
	ret, err := httputil.DoRequest(request.Method, url, string(data), map[string]string{
		"x_user_id": userId,
		"device_id": deviceId,
	})

	if err != nil {
		log.Error(fmt.Sprintf("Handler err: %v", err))
		return
	}

	var h gin.H
	_ = json.Unmarshal([]byte(ret), &h)
	ctx.JSON(http.StatusOK, h)
	return
}
